<?php

namespace App\Models\Traits;

use App\Models\Topic;
use Illuminate\Support\Facades\Cache;

trait HotTopicHelper
{
    // 缓存相关配置
    protected $cache_key = 'laravel_blog_hot_topics';
    protected $cache_expire_in_seconds = 65 * 60;

    public function getHotTopicsCached($limit = 6)
    {
        // 尝试从缓存中取出 cache_key 对应的数据。如果能取到，便直接返回数据。
        // 否则运行匿名函数中的代码来取出活跃用户数据，返回的同时做了缓存。
        return Cache::remember($this->cache_key, $this->cache_expire_in_seconds, function () use ($limit) {
            return $this->queryHotTopics($limit);
        });
    }

    public function cacheHotTopics()
    {
        $hot_topics = $this->queryHotTopics();
        Cache::put($this->cache_key, $hot_topics, $this->cache_expire_in_seconds);
    }

    private function queryHotTopics($limit)
    {
        return Topic::with(['category', 'user'])
            ->orderByDesc('reply_count')
            ->orderByDesc('view_count')
            ->where('publish_at', '<', now())
            ->limit($limit)
            ->get();
    }

}
